<template>
  <el-form :inline="true" :model="queryParam" class="demo-form-inline">
    <el-form-item label="用户名">
      <el-input v-model="queryParam.userName" placeholder="用户名" clearable />
    </el-form-item>
    <el-form-item label="昵称">
      <el-input v-model="queryParam.nickName" placeholder="昵称" clearable />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit">查询</el-button>
    </el-form-item>
  </el-form>
  <div>
    <el-button type="primary" :icon="Plus" @click="createUser" v-hasRole="['admin']" />
    <el-button type="primary" :icon="Share" v-hasRole="['hr']" />
    <el-button type="primary" :icon="Delete" />
    <el-button type="primary" :icon="Search">Search</el-button>
    <el-button type="primary">
      Upload<el-icon class="el-icon--right">
        <Upload />
      </el-icon>
    </el-button>
  </div>
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500" :before-close="handleClose">
    <template #footer>
      <div class="dialog-footer">
        <el-form ref="formRef" :model="userForm" label-width="80px" :rules="loginRules">
          <el-form-item label="用户名" prop="userName">
            <el-input v-model="userForm.userName" placeholder="请输入用户"></el-input>
          </el-form-item>
          <el-form-item label="昵称" prop="nickName">
            <el-input v-model="userForm.nickName" type="text" placeholder="请输入昵称"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="userForm.email" type="email" placeholder="请输入邮箱"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password" v-if="userForm.userId === null">
            <el-input v-model="userForm.password" type="password" placeholder="请输入密码" show-password></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPwd" v-if="userForm.userId === null">
            <el-input v-model="userForm.confirmPwd" type="password" placeholder="请输入密码" show-password></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmitDialog">Create</el-button>
            <el-button @click="dialogVisible = false">Cancel</el-button>
          </el-form-item>
        </el-form>
      </div>
    </template>
  </el-dialog>
  <el-table ref="tableRef" row-key="userId" :data="tableData" v-loading="loading" style="width: 100%">
    <el-table-column prop="userName" label="用户名" />
    <el-table-column prop="nickName" label="昵称" />
    <el-table-column prop="email" label="邮箱" />
    <el-table-column label="操作">
      <template #default="scope">
        <el-button size="small" @click="handleEdit(scope.$index, scope.row)"> 编辑 </el-button>
        <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">
          删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-container style="margin: 20px">
    <el-pagination background layout="prev, pager, next" @current-change="changePage" :total="total" />
  </el-container>
</template>

<script setup>
import { onMounted, ref } from "vue";
import { listUser, addUser, getById, editUser, deleteById } from "@/api/user";
import { ElMessage, ElMessageBox } from "element-plus";
import { Delete, Plus, Search, Share, Upload } from "@element-plus/icons-vue";

const queryParam = ref({
  size: 8,
  page: 0,
  userName: "",
  nickName: "",
  email: "",
});
const tableRef = ref();
const tableData = ref([]);
const loading = ref(true);
const total = ref(0);
const dialogVisible = ref(false);
const formRef = ref();
let operation = () => { };
class User {
  userId = null;
  userName = "";
  nickName = "";
  password = "";
  confirmPwd = "";
}
const userForm = ref(new User());
const dialogTitle = ref("");
const openDialog = (title) => {
  reset();
  dialogTitle.value = title;
  dialogVisible.value = true;
};
// 修改用户
const handleEdit = (index, row) => {
  getById(row.userId).then((res) => {
    operation = editUser;
    openDialog("修改用户");
    userForm.value = res.data;
  });
};
// 新增用户
const createUser = () => {
  operation = addUser;
  openDialog("新增用户");
};
// 删除用户
const handleDelete = (index, row) => {
  console.log(index, row);
  getById(row.userId).then((res) => {
    userForm.value = res.data;
    ElMessageBox.confirm(`是否确认删除用户：${row.userName}？`, "Warning", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        deleteById(userForm.value.userId).then(() => {
          getList();
          ElMessage({
            type: "success",
            message: `已删除用户：${row.nickName}`,
          });
        });
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "取消删除操作",
        });
      })
  });
};

const reset = () => {
  userForm.value = new User();
};
const onSubmitDialog = () => {
  //  v-if="userForm.userId === null
  if (userForm.value.userId === null) {
    if (userForm.value.password !== userForm.value.confirmPwd) {
      ElMessage.error("两次密码输入不一致");
      return;
    }
  }
  // 提交
  delete userForm.value.confirmPwd;
  operation(userForm.value).then(() => {
    getList();
  });
  dialogVisible.value = false;
};
const onSubmit = () => {
  getList();
};
const getList = () => {
  loading.value = true;
  listUser(queryParam.value)
    .then((res) => {
      tableData.value = res.data.content;
      total.value = res.data.totalElements;
      queryParam.value.size = res.data.size;
    })
    .catch((error) => {
      console.error("获取用户列表失败:", error);
      ElMessage.error("加载用户列表失败");
    })
    .finally(() => {
      loading.value = false;
    });
};

onMounted(() => {
  getList();
});

const changePage = (current) => {
  queryParam.value.page = current - 1;
  getList();
};
</script>
<style scoped>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>
